﻿using Autofac;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MyWeb.ServiceBus.Model;
using MyWeb.ServiceBus.Services.Db;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace MyWeb.ServiceBus.Extensions.Db
{
    /// <summary>
    /// EF 上下文启动服务
    /// </summary>
    public static class EFDbContextSetup
    {
        // Microsoft.Extensions.Logging.Console
        //private static readonly ILoggerFactory _loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
        /// <summary>
        /// 添加EF Core 上下文注入
        /// </summary>
        /// <param name="services"></param>
        public static void AddEFDbContextSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            string conn = "Data Source=127.0.0.1;Initial Catalog=Gateway;User ID=sa;Password=123456;TrustServerCertificate=true";

            services.AddDbContext<Context>(options =>
                options.UseSqlServer(conn, options => {
                    options.MigrationsAssembly("MyWeb.ServiceBus");
                    options.EnableRetryOnFailure();
                    }
                )
                //.UseLoggerFactory(_loggerFactory)  // 启用日志记录
                //.EnableSensitiveDataLogging() // 如果需要输出参数值，请启用此选项
            );
        }
        /// <summary>
        /// 使用autofac注入 EFCore
        /// </summary>
        /// <param name="builder"></param>
        public static void AddEFDbRegister(this ContainerBuilder builder)
        {
            // 使用已配置的 DbContext 注册 EF 相关服务
            //builder.Register(c =>
            //{
            //    var dbContextOptions = c.Resolve<DbContextOptions<Context>>();

            //    return new Context(dbContextOptions);
 
                
            //})
            //    .As<Context>()
            //    .InstancePerLifetimeScope();
        }
    }
}
